summaryrefslogtreecommitdiff
path: root/src/pages/shop/product/[slug].js
blob: 2b54a1e057b3e8b92fe03d605afed7951220ecb8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import Link from "../../../components/Link";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import Header from "../../../components/Header";
import apiOdoo from "../../../helpers/apiOdoo";
import { createSlug, getIdFromSlug } from "../../../helpers/slug";
import currencyFormat from "../../../helpers/currencyFormat";
import { LazyLoadImage } from "react-lazy-load-image-component";
import "react-lazy-load-image-component/src/effects/blur.css";
import ProductSlider from "../../../components/product/ProductSlider";
import Layout from "../../../components/Layout";
import { createOrUpdateItemCart } from "../../../helpers/cart";
import toast from "react-hot-toast";

export async function getServerSideProps( context ) {
  const { slug } = context.query;
  let product = await apiOdoo('GET', '/api/v1/product/' + getIdFromSlug(slug));
  if (product.length == 1) {
    product = product[0];
    product.description = product.description.replaceAll('<p>', '||p||');
    product.description = product.description.replaceAll('</>', '||/p||');
    product.description = product.description.replace(/(<([^>]+)>)/gi, ' ');
    product.description = product.description.replaceAll('||p||', '<p>');
    product.description = product.description.replaceAll('||/p||', '</p>');
    product.description = product.description.trim();
  }
  return { props: { product } };
}

export default function ProductDetail({ product }) {
  const router = useRouter();
  const { slug } = router.query;
  const [selectedVariant, setSelectedVariant] = useState("");
  const [quantity, setQuantity] = useState("1");
  const [similarProducts, setSimilarProducts] = useState(null);
  const [activeVariant, setActiveVariant] = useState({
    id: product.id,
    code: product.code,
    price: product.lowest_price,
    stock: product.stock_total,
    weight: product.weight,
    attributes: '',
  });
  
  useEffect(() => {
    if (product.variants.length == 1) {
      setSelectedVariant(product.variants[0].id);
    }
  }, [product]);

  useEffect(() => {
    setSimilarProducts(null);
    const getSimilarProducts = async () => {
      const dataSimilarProducts = await apiOdoo('GET', `/api/v1/product/${getIdFromSlug(slug)}/similar?limit=20`);
      setSimilarProducts(dataSimilarProducts);
    }
    if (slug) getSimilarProducts();
  }, [slug]);

  useEffect(() => {
    if (selectedVariant != '') {
      let newActiveVariant = product.variants.filter((variant) => {
        return variant.id == selectedVariant;
      });
  
      if (newActiveVariant.length == 1) {
        newActiveVariant = newActiveVariant[0];
        setActiveVariant({
          id: newActiveVariant.id,
          code: newActiveVariant.code,
          price: newActiveVariant.price,
          stock: newActiveVariant.stock,
          weight: newActiveVariant.weight,
          attributes: newActiveVariant.attributes.join(', '),
        });
      }
    }
  }, [selectedVariant, product]);

  let onchangeVariant = (e) => {
    setSelectedVariant(e.target.value);
    setQuantity("1");
  }

  let addItemToCart = () => {
    if (product.variant_total > 1 && !selectedVariant) {
      toast.error('Pilih varian terlebih dahulu untuk menambahkan ke keranjang', { duration: 2000 });
      return false;
    }

    if (quantity > 0) {
      toast.success('Berhasil menambahkan ke keranjang', { duration: 1500 });
      createOrUpdateItemCart(activeVariant.id, parseInt(quantity));
    } else {
      toast.error('Jumlah barang yang ditambahkan minimal 1 pcs', { duration: 2000 });
    }

    return true;
  }

  return (
    <>
      <Header title={`${product.name} - Indoteknik`}/>
      <Layout>
        <LazyLoadImage effect="blur" src={product.image} alt={product.name} className="border-b border-gray_r-6 w-full h-[300px] object-contain object-center bg-white" />
        <div className="p-4 pb-10">
          <Link href={'/shop/brands/' + createSlug(product.manufacture.name, product.manufacture.id)}>
            {product.manufacture.name ?? '-'}
          </Link>
          <h1 className="h2 mt-2 mb-3">{product.name}{activeVariant.attributes ? ' - ' + activeVariant.attributes : ''}</h1>

          {product.variant_total > 1 && !selectedVariant && product.lowest_price.price > 0 ? (
            <p className="text-caption-2 text-gray-800 mb-1">Harga mulai dari:</p>
          ) : ''}

          {product.lowest_price.discount_percentage > 0 ? (
            <div className="flex gap-x-1 items-center mb-1">
              <p className="text-caption-2 text-gray_r-11 line-through">{currencyFormat(activeVariant.price.price)}</p>
              <span className="badge-red">{activeVariant.price.discount_percentage}%</span>
            </div>
          ) : ''} 

          {product.lowest_price.price > 0 ? (
            <p className="text-body-lg font-semibold">{currencyFormat(activeVariant.price.price_discount)}</p>
          ) : (
            <p className="text-gray_r-11">Dapatkan harga terbaik, <a href="">hubungi kami.</a></p>
          )}

          <div className="flex gap-x-2 mt-5">
            <div className="w-9/12">
              <label className="form-label mb-1">Pilih: <span className="text-gray-800">{product.variant_total} Varian</span></label>
              <select name="variant" className="form-input" value={selectedVariant} onChange={onchangeVariant} >
                <option value="" disabled={selectedVariant != "" ? true : false}>Pilih Varian...</option>
                {product.variants.length > 1 ? (
                  product.variants.map((variant) => {
                    return (
                      <option key={variant.id} value={variant.id}>{variant.attributes.join(', ')}</option>
                    );
                  })
                ) : (
                  <option key={product.variants[0].id} value={product.variants[0].id}>{product.variants[0].name}</option>
                )}
              </select>
            </div>
            <div className="w-3/12">
              <label htmlFor="quantity" className="form-label mb-1">Jumlah</label>
              <input type="number" name="quantity" id="quantity" className="form-input text-center is-invalid" value={quantity} onChange={(e) => setQuantity(e.target.value)} />
            </div>
          </div>

          <div className="flex gap-x-2 mt-2">
            <button className="btn-light w-full">+ Quotation</button>
            <button 
              className="btn-yellow w-full" 
              onClick={addItemToCart} 
              disabled={(product.lowest_price.price == 0 ? true : false)}
            >
              + Keranjang
            </button>
          </div>

          <div className="mt-10">
            <h2 className="font-bold mb-2">Detail Produk</h2>
            <div className="flex py-2 justify-between items-center gap-x-1 border-b border-gray-300">
              <h3 className="text-gray-900">Jumlah Varian</h3>
              <p className="text-gray-800">{product.variant_total} Varian</p>
            </div>
            <div className="flex py-2 justify-between items-center gap-x-1 border-b border-gray-300">
              <h3 className="text-gray-900">Nomor SKU</h3>
              <p className="text-gray-800" id="sku_number">SKU-{activeVariant.id}</p>
            </div>
            <div className="flex py-2 justify-between items-center gap-x-1 border-b border-gray-300">
              <h3 className="text-gray-900">Part Number</h3>
              <p className="text-gray-800" id="part_number">{activeVariant.code}</p>
            </div>
            <div className="flex py-2 justify-between items-center gap-x-1 border-b border-gray-300">
              <h3 className="text-gray-900">Stok</h3>
              <p className="text-gray-800" id="stock">
                {activeVariant.stock > 0 ? (activeVariant.stock > 5 ? 'Lebih dari 5' : 'Kurang dari 5') : '0'}
              </p>
            </div>
            <div className="flex py-2 justify-between items-center gap-x-1 border-b border-gray-300">
              <h3 className="text-gray-900">Berat Barang</h3>
              <p className="text-gray-800" id="weight">{activeVariant.weight > 0 ? activeVariant.weight : '1'} KG</p>
            </div>
          </div>

          <div className="mt-10">
            <h2 className="font-bold mb-4">Deskripsi Produk</h2>
            <div className="text-gray-800 leading-7" dangerouslySetInnerHTML={{__html: (product.description != '' ? product.description : 'Belum ada deskripsi produk.')}}></div>
          </div>

          <div className="mt-10">
            <h2 className="font-bold mb-4">Produk Lainnya</h2>
            <ProductSlider products={similarProducts}/>
          </div>
        </div>
      </Layout>
    </>
  );
}